package com.pro.framework.json.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class JsonService implements IJsonService {
    private final ObjectMapper objectMapper;

    public JsonService(ObjectMapper objectMapper) {
        // 构造请求体
        this.objectMapper = objectMapper;
    }

    @Override
    @SneakyThrows
    public String serialize(Object obj) {
        return objectMapper.writeValueAsString(obj);
    }

    @Override
    @SneakyThrows
    public <T> T deserialize(String json, Class<T> clazz, Class<?>... clazzOther) {
        if (clazzOther.length==0) {
            return objectMapper.readValue(json, clazz);
        } else {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(clazz, clazzOther);
            return objectMapper.readValue(json, javaType);
        }
    }
}
